package com.jinyou.chengfengshop.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.jinyou.chengfengshop.Constant.AppUrl;
import com.jinyou.chengfengshop.OkHttpUtils.CallBackUtil;
import com.jinyou.chengfengshop.OkHttpUtils.OkhttpUtil;
import com.jinyou.chengfengshop.R;
import com.jinyou.chengfengshop.bean.orderNoBean;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import okhttp3.Call;

/**
 * Created by zhuzhiqiang on 2018/9/25.
 */
// MD5:  BB:04:8A:83:8C:CC:59:F7:40:80:E3:74:C2:05:B6:CB
//         SHA1: C7:29:D2:C4:2F:45:E5:96:7C:AF:40:DC:39:DE:D9:D2:A5:37:B7:BC
//         SHA256: 95:D8:C5:C5:1D:8D:F4:73:94:4A:50:DE:26:63:73:63:94:20:54:D4:5C:1A:46:12:7D:47:08:2F:31:22:37:DD

public class RiderAddressActivity extends AppCompatActivity{

    private MapView mMapView = null;
    private AMap aMap = null;
    private CameraUpdate cameraUp;
    private String token;
    private TextView back_tv;

    private orderNoBean odb;

    private static final int LOCATION_CODE = 1;
    private LocationManager lm;//【位置管理】
    private ImageView phone_img;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rider);
        odb = (orderNoBean) getIntent().getSerializableExtra("info");
        SharedPreferences sh = getSharedPreferences("user", Context.MODE_PRIVATE);
        token = sh.getString("tocken","");

        mMapView = (MapView) findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);// 此方法必须重写
        //初始化地图控制器对象

        if (aMap == null) {
            aMap = mMapView.getMap();
            aMap.setMapType(AMap.MAP_TYPE_NORMAL);
        }

        back_tv = (TextView) findViewById(R.id.back_tv);
        back_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

//        Uri uri = Uri.parse(odb.getRiderImage());
//        fab.setImageURI(uri);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent dialIntent =  new Intent(Intent.ACTION_DIAL,Uri.parse("tel:" + odb.getRiderTel()));//跳转到拨号界面，同时传递电话号码
                startActivity(dialIntent);
            }
        });

        phone_img = (ImageView) findViewById(R.id.phone_img);
        phone_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent dialIntent =  new Intent(Intent.ACTION_DIAL,Uri.parse("tel:" + odb.getRiderTel()));//跳转到拨号界面，同时传递电话号码
                startActivity(dialIntent);
            }
        });



        quanxian();

    }


    public void quanxian(){
        lm = (LocationManager) RiderAddressActivity.this.getSystemService(RiderAddressActivity.this.LOCATION_SERVICE);
        boolean ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (ok) {//开了定位服务
            if (ContextCompat.checkSelfPermission(RiderAddressActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                Log.e("BRG","没有权限");
                // 没有权限，申请权限。
                // 申请授权。
                ActivityCompat.requestPermissions(RiderAddressActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);


            } else {
                getRiderLocation(odb.getRiderTel());

            }
        } else {
            Log.e("BRG","系统检测到未开启GPS定位服务");
            Toast.makeText(RiderAddressActivity.this, "系统检测到未开启GPS定位服务", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, 1315);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case LOCATION_CODE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 权限被用户同意。
                    getRiderLocation(odb.getRiderTel());

                } else {
                    // 权限被用户拒绝了。
                    Toast.makeText(RiderAddressActivity.this, "定位权限被禁止，相关地图功能无法使用！",Toast.LENGTH_LONG).show();
                }

            }
        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }


    //获取骑手位置
    private void getRiderLocation(String userName){

            HashMap<String,String> paramsMap = new HashMap<>();
            paramsMap.put("token",token);
            paramsMap.put("sysCustomer","o2o-chengfeng");
            paramsMap.put("username",userName);

            OkhttpUtil.okHttpPost(AppUrl.RIDER_LOCAL, paramsMap, new CallBackUtil.CallBackString() {
                @Override
                public void onFailure(Call call, Exception e) {
                    Toast.makeText(RiderAddressActivity.this,"失败",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onResponse(String response) {//请求成功时调用，执行在UI线程
                    try {

                        JSONObject obj = new JSONObject(response);
                        int code = obj.getInt("status");
                        if(code == 1){
                            JSONObject info = obj.getJSONObject("info");


                            setRiderMarder(info.getDouble("lng"),info.getDouble("lat"));

                        }else {
                            Toast.makeText(RiderAddressActivity.this,obj.getString("error"),Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });



    }

    private void setRiderMarder(double lng,double lat){
        MarkerOptions markerOption = new MarkerOptions();

        Log.d("setRiderMarder","lng"+lng+"lat"+lat);
        LatLng latLng = new LatLng(lat,lng);
        markerOption.position(latLng);

        markerOption.draggable(true);//设置Marker可拖动
        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(),R.drawable.icon_marker)));
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.setFlat(true);//设置marker平贴地图效果

        aMap.addMarker(markerOption);

        //改变可视区域为指定位置        //CameraPosition4个参数分别为位置，缩放级别，目标可视区域倾斜度，可视区域指向方向（正北逆时针算起，0-360）
        cameraUp= CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng,16,0,0));
        aMap.moveCamera(cameraUp);//地图移向指定区域
    }


}
